//
//  AppDelegate.m
//  ECSDKDemo_OC
//
//  Created by jiazy on 14/12/4.
//  Copyright (c) 2014年 ronglian. All rights reserved.
//

#import "AppDelegate.h"
#import "ECDeviceHeaders.h"
#import "MainViewController.h"
#import "DemoGlobalClass.h"
#import "AddressBookManager.h"
#import "CustomEmojiView.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import "WXApi.h"
#import "LYTabBarController.h"
#import "LYSubjectListDBTool.h"
#import "LYCityDataDBTool.h"
//#import "LYUserLoginInfo.h"
#import "LYLoginInfoModel.h"
#import <UMSocial.h>
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaSSOHandler.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiManager.h"
#import "UPPaymentControl.h"
#import "VVYPayManager.h"
#import "JPUSHService.h"
#import "LYClassWebViewController.h"
#import "LYVideoWebViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import "LYWebViewController.h"
#import "LYTestViewController.h"
#import "LSYGuideMainView.h"
#define LOG_OPEN 0

NSString *const dbdata = @"dbdata";

@interface AppDelegate ()

@property (nonatomic, strong) NSDateFormatter *dataformater;

@property (nonatomic, strong) BMKMapManager *manager;
@end

@implementation AppDelegate

/**
 *  第三方回调
 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //友盟回调
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        //微信回调
        result = [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        if (result == FALSE) {
            //支付宝回调
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                
            }];
            
            //银联
            [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
                
                [[VVYPayManager sharedManager] handleUPPayCallBackInfoCode:code data:data];
                
            }];

            
        }
        
        
    }
    
    return YES;
    
}


/**
 *  初始化友盟
 */
- (void)setUpUMSocial{
    
    //设置友盟appkey
    [UMSocialData setAppKey:UMSocialAppKey];
    
    //隐藏成功自带回调
    [UMSocialConfig setFinishToastIsHidden:NO position:UMSocialiToastPositionCenter];
    
    
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:UMWechatKey appSecret:UMWechatSecret url:SharedLink];
    
    //设置QQ AppId、appSecret，分享url
    [UMSocialQQHandler setQQWithAppId:UMQQID appKey:UMQQKey url:SharedLink];
    
    //微博
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:UMWeiBoKey
                                              secret:UMWeiBoSecret
                                         RedirectURL:UMWeiBoCallBack];
    
    //初始化分享标题
    [UMSocialData defaultData].extConfig.wechatSessionData.title = ShareTitle;
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = ShareTitle;
    [UMSocialData defaultData].extConfig.qqData.title = ShareTitle;
    [UMSocialData defaultData].extConfig.qzoneData.title = ShareTitle;
}

/**
 *  初始化百度地图
 */
- (void)setUpBaiduMap{

    _manager = [[BMKMapManager alloc] init];
    BOOL ret = [_manager start:LYMapKey  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }

}

/**
 *  初始化微信支付
 */
- (void)setUpWXPay{
    
    [WXApi registerApp:UMWechatKey withDescription:@"艺术"];
    
}

/**
 *  初始化极光推送
 */
- (void)setUpJPushWithLaunchOptions:(NSDictionary *)launchOptions{

    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //       categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories    nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions
                           appKey:JPushAPPKey
                          channel:@"AppStore"
                 apsForProduction:NO
            advertisingIdentifier:nil];


}


- (void)redirectNSLogToDocumentFolder {
    
#if LOG_OPEN
    if(isatty(STDOUT_FILENO)){
        return;
    }
    
    UIDevice *device = [UIDevice currentDevice];
    if([[device model] hasSuffix:@"Simulator"]){ //在模拟器不保存到文件中
        return;
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName =[NSString stringWithFormat:@"%@.log", [self.dataformater stringFromDate:[NSDate date]]];
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
#endif

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
    LYLoginInfoModel *login = [VVYSaveDataManager getDataWithKey:LYUserLoginInfo];
    self.token = login.token;
    
    NSLog(@"%@",self.token);
    UIWindow *window = [[UIWindow alloc] initWithFrame:LYScreenBounds];
    
    window.rootViewController = [[LYTabBarController alloc] init];
    
    [[VVYCheckStatus sharedInstance] checkIsLogin];
    
    self.window = window;
    [window makeKeyAndVisible];
    
    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [CustomEmojiView shardInstance];
    });

    

    
    //初始化极光推送
    [self setUpJPushWithLaunchOptions:launchOptions];
    
    //初始化友盟
    [self setUpUMSocial];
    
    //初始化微信
    [self setUpWXPay];

    //初始化百度地图
    [self setUpBaiduMap];
    
    NSString *flag = [[NSUserDefaults standardUserDefaults] objectForKey:dbdata];
    
    if (!flag) {
        [self getDBData];

    }
    

    

#if !TARGET_IPHONE_SIMULATOR
    self.dataformater = [[NSDateFormatter alloc] init];
    [self.dataformater setDateFormat:@"yyyyMMddHH"];

    
    
    
    //iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        
        UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init];
        action.title = @"查看消息";
        action.identifier = @"action1";
        action.activationMode = UIUserNotificationActivationModeForeground;
        
        UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
        category.identifier = @"alert";
        [category setActions:@[action] forContext:UIUserNotificationActionContextDefault];

        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:[NSSet setWithObjects:category, nil]];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    } else {
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
    
#endif
    
    [self redirectNSLogToDocumentFolder];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectStateChanged:) name:KNOTIFICATION_onConnected object:nil];
  
    #warning 设置代理
    [ECDevice sharedInstance].delegate = [DeviceDelegateHelper sharedInstance];
    
    LYUserInfoModel *userInfo = [VVYSaveDataManager getDataWithKey:KEY_USERMESSAGE];
    [LYPublicMethod  loginRongLianYunWithLoginInfo:userInfo];

//
//    [self shareSDK];
//    UINavigationController * rootView = nil;
//    //是否有登录信息
//    [DemoGlobalClass sharedInstance].isAutoLogin = [self getLoginInfo];
//    if ([DemoGlobalClass sharedInstance].isAutoLogin) {
//        
//        //打开本地数据库
//        [[DeviceDBHelper sharedInstance] openDataBasePath:[DemoGlobalClass sharedInstance].userName];
////        self.mainView = [[MainViewController alloc] init];
////        rootView = [[UINavigationController alloc] initWithRootViewController:_mainView];
//    } else {
//    }
//
//    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
//    self.window.rootViewController = rootView;
//    
//    [self.window makeKeyAndVisible];
    
//    NSLog(@"测试 application didFinishLaunchingWithOptions");
    
    [LSYGuideMainView showGuideMainViewWithButtonPressedBlock:^(NSInteger buttonIndex, UIButton *button) {
        
    }];
    
    return YES;
}

- (void)shareSDK {
    [ShareSDK registerApp:@"1036529846b88" activePlatforms:@[@(SSDKPlatformTypeWechat)] onImport:^(SSDKPlatformType platformType) {
        switch (platformType) {
            case SSDKPlatformTypeWechat:
                [ShareSDKConnector connectWeChat:[WXApi class]];
                break;
            default:
                break;
        }
    } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
        switch (platformType) {
            case SSDKPlatformTypeWechat:
                [appInfo SSDKSetupWeChatByAppId:@"wx718c6680d68744a4"
                                      appSecret:@"dc60d64d62987255adc241917bdae597"];
                break;
            default:
                break;
        }
    }];
}

-(void)toast:(NSString*)message {
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = message;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];
}

-(void)updateSoftAlertViewShow:(NSString*)message isForceUpdate:(BOOL)isForce {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"新版本发布" message:message delegate:self cancelButtonTitle:isForce?nil:@"下次更新" otherButtonTitles:@"更新", nil];
    alert.tag = 100;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != alertView.cancelButtonIndex) {
        if (alertView.tag == 100) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://dwz.cn/F8pPd"]];
            exit(0);
        }
    }
}

+(AppDelegate*)shareInstance {
    return [[UIApplication sharedApplication] delegate];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    NSLog(@"推送的内容：%@",notificationSettings);
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    
    
    if (application.applicationState == UIApplicationStateInactive) {
        
        //推送消息处理
        [self handleRemoteNotificationWithInfo:userInfo];
        
    }
    
    self.callid = nil;
    NSString *userdata = [userInfo objectForKey:@"c"];
    NSLog(@"远程推送userdata:%@",userdata);
    if (userdata) {
        NSDictionary*callidobj = [NSJSONSerialization JSONObjectWithData:[userdata dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"远程推送callidobj:%@",callidobj);
        if ([callidobj isKindOfClass:[NSDictionary class]]) {
            self.callid = [callidobj objectForKey:@"callid"];
        }
    }
    
    NSLog(@"远程推送 callid=%@",self.callid);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


#warning 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    #warning 将获取到的token传给SDK，用于苹果推送消息使用
    [[ECDevice sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#warning 注册deviceToken失败；此处失败，与SDK无关，一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.failToRegisterApns", Fail to register apns)
                                                    message:error.description
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                          otherButtonTitles:nil];
    [alert show];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    NSInteger count = 0;
    UINavigationController * rootView = (UINavigationController*)self.window.rootViewController;
    if ([rootView.viewControllers[0] isKindOfClass:[MainViewController class]]) {
        count = [[IMMsgDBAccess sharedInstance] getUnreadMessageCountFromSession];
    } 
    application.applicationIconBadgeNumber = count;
    
    [[ECDevice sharedInstance] setAppleBadgeNumber:count completion:^(ECError *error) {
        
    }];
    usleep(10);
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
  
    [DeviceDelegateHelper sharedInstance].isB2F = YES;
    [DeviceDelegateHelper sharedInstance].preDate = nil;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [DeviceDelegateHelper sharedInstance].preDate = [NSDate date];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



-(BOOL)getLoginInfo {
    NSString *loginInfo = [DemoGlobalClass sharedInstance].userName;
    if (loginInfo.length>0) {
        return YES;
    }
    return NO;
}

//登录页面和主页面的切换
-(void)connectStateChanged:(NSNotification *)notification {
    ECError* error = notification.object;
    UINavigationController * rootView = (UINavigationController*)self.window.rootViewController;
    if (error) {
        [DemoGlobalClass sharedInstance].isLogin = NO;
        
        if (error.errorCode == ECErrorType_KickedOff || error.errorCode == 10) {
            
//            NSMutableArray *navArray = [NSMutableArray arrayWithArray:rootView.viewControllers];
//            [navArray removeAllObjects];
//            rootView.viewControllers = navArray;
            
//            [rootView popToRootViewControllerAnimated:true];
            
            [DemoGlobalClass sharedInstance].userName = nil;
            
//            if (error.errorCode == ECErrorType_KickedOff){
//                UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:@"警告" message:error.errorDescription delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                [alertView show];
//            }
            
        } else if (error.errorCode == ECErrorType_NoError) {
            
            [DemoGlobalClass sharedInstance].isLogin = YES;
            [DemoGlobalClass sharedInstance].isHiddenLoginError = NO;
            
        } else if (error.errorCode != ECErrorType_Connecting
                && error.errorCode != ECErrorType_TokenAuthFailed
                && error.errorCode != ECErrorType_AuthServerException
                && error.errorCode != ECErrorType_ConnectorServerException) {
            
            if (![DemoGlobalClass sharedInstance].isHiddenLoginError) {
                [DemoGlobalClass sharedInstance].isHiddenLoginError = YES;
//                [self toast:[NSString stringWithFormat:@"登录失败",(int)error.errorCode]];
//                   [self toast:[NSString stringWithFormat:@"登录失败"]];

//                []
            }
        }
    }

    
    self.window.rootViewController = rootView;
}

/**
 *  请求城市数据
 */
- (void)getCitydataWithType:(cityDataType)type{
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSString *urlStr = nil;
    
    switch (type) {
        case cityDataTypeNormal:
            urlStr = @"http://esj.zzzedu.cn/artphp/?s=/UserApi/Region/lists";
            
            break;
        case cityDataTypeOpen:
            urlStr = @"http://esj.zzzedu.cn/artphp/?s=/UserApi/Region/selected_list";
            break;
    }
    
    
    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlStr]completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (!error) {
            
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil][@"data"][@"region_list"];
            
            [LYCityDataDBTool saveCityData:array withType:type];
        }
        
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    
    
    [task resume];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

/**
 *  获取科目数据
 */
- (void)getSubjectData{
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSString *urlStr = @"http://esj.zzzedu.cn/artphp/?s=/UserApi/Subject/lists";
    
    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlStr]completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil][@"data"][@"subject_list"];
            
            [LYSubjectListDBTool saveSubData:array];
            
        }
        dispatch_semaphore_signal(semaphore);
    }];
    
    [task resume];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

/**
 *  获取数据库数据
 */
- (void)getDBData{
    
    [MBProgressHUD showMessage:@"正在加载数据"];
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_group_async(group, queue, ^{
        
        [self getCitydataWithType:cityDataTypeOpen];
        
    });
    
    dispatch_group_async(group, queue, ^{
        
        [self getCitydataWithType:cityDataTypeNormal];
        
    });
    dispatch_group_async(group, queue, ^{
        
        [self getSubjectData];
        
    });
    
    dispatch_group_notify(group, queue, ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [[NSUserDefaults standardUserDefaults] setObject:@"whatever" forKey:dbdata];
        });
        
    });
    
}

#pragma mark - 远程推送处理
- (void)handleRemoteNotificationWithInfo:(NSDictionary *)info{
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        UITabBarController *tabbarVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        if (![tabbarVC isKindOfClass:[UITabBarController class]]) {
            return ;
        }
        
        UINavigationController *nav = tabbarVC.selectedViewController;
        
        NSString *type = info[@"type"];
        NSString *data = info[@"data"];
        
        
        if ([type isEqualToString:@"course"]) {
            
            LYClassWebViewController *classVC = [LYClassWebViewController classWebVCWithID:data];
            [nav pushViewController:classVC animated:YES];
            
        }else if([type isEqualToString:@"video"]){
            
            LYVideoWebViewController *videoVC = [LYVideoWebViewController videoWebVCWithID:data];
            [nav pushViewController:videoVC animated:YES];
            
        }else if([type isEqualToString:@"article"]){
        
            LYWebViewController *article = [LYWebViewController webVCWithID:data andType:WebTypeArtical];
            
            [nav pushViewController:article animated:YES];
        }else if([type isEqualToString:@"testing"]){
        
            
            LYTestViewController *test = [LYTestViewController testVCWithTestID:data];
            [nav pushViewController:test animated:YES];
        };
        
    });
    
}

@end
